package com.briup.client;

import com.briup.entity.Environment;
import com.briup.exception.CodeStatus;
import com.briup.exception.EnvException;
import com.briup.interfaces.Client;
import com.briup.interfaces.Configuration;
import com.briup.interfaces.Log;

import java.io.*;
import java.net.Socket;
import java.util.Collection;
import java.util.Properties;

/**
 * 客户端发送任务的逻辑实现
 */
public class ClientImpl implements Client {
    private String ip;
    private int port;
    private Log log;

    public void init(Properties properties) {
        ip = properties.getProperty("ip");
        port = Integer.parseInt(properties.getProperty("port"));
    }

    @Override
    public void setConfiguration(Configuration configuration) {
        log = configuration.getLog();
    }

    @Override
    public void send(Collection<Environment> coll) {
        Socket socket = null;
        ObjectOutputStream oos = null;
        try {
            socket = new Socket(ip, port);
            // 准备对象输出流，写出去集合
            oos = new ObjectOutputStream(socket.getOutputStream());
            oos.writeObject(coll);
            oos.flush();
        } catch (IOException e) {
            log.error(e.getMessage());
            throw new EnvException(CodeStatus.IO_EXCEPTION);
        } finally {
            if (oos != null) {
                try {
                    oos.close();
                } catch (IOException e) {
                    log.error(e.getMessage());
                    throw new EnvException(CodeStatus.IO_EXCEPTION);
                }
            }
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    log.error(e.getMessage());
                    throw new EnvException(CodeStatus.IO_EXCEPTION);
                }
            }
        }
    }
}
